package com.dragon.logical.service.auth.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dragon.common.model.ResultCode;
import com.dragon.common.model.exception.CustomException;
import com.dragon.common.util.CovertUtil;
import com.dragon.logical.service.auth.PositionService;
import com.dragon.repository.entity.Admin;
import com.dragon.repository.entity.AdminPosition;
import com.dragon.repository.entity.Position;
import com.dragon.repository.mapper.AdminPositionMapper;
import com.dragon.repository.mapper.PositionMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 岗位表 服务实现类
 * </p>
 *
 * @author sy
 * @since 2023-06-14
 */
@Service
public class PositionServiceImpl extends ServiceImpl<PositionMapper, Position> implements PositionService {

    @Autowired
    PositionMapper mapper;

    @Autowired
    AdminPositionMapper positionMapper;

    @Override
    public List<Position> ListP(Integer departmentId, String search) {
        QueryWrapper<Position> wrapper = new QueryWrapper<>();
        wrapper.lambda()
                .eq(departmentId != null, Position::getDepartmentId, departmentId)
                .or().like(StrUtil.isNotBlank(search), Position::getName, search);
        List<Position> positions = mapper.selectList(wrapper);
        return positions;
    }

    @Override
    public Page<Position> selectPageList(Integer departmentId, String name, Integer page, Integer limit) {
        Page<Position> positionPage = new Page<>(page, limit);
        QueryWrapper<Position> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda()
                .eq(departmentId != null, Position::getDepartmentId, departmentId)
                .like(StrUtil.isNotBlank(name), Position::getName, name);
        Page<Position> pageList = mapper.selectPage(positionPage, queryWrapper);
        return pageList;
    }

    @Override
    public void insert(Position position) {
        QueryWrapper<Position> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(Position::getName, position.getName());
        //检测岗位名称是否存在
        Position one = mapper.selectOne(queryWrapper);
        if (one != null) {
            throw new CustomException(ResultCode.DATA_ALREADY_EXISTS);
        }
        //如果提交的数据为1的话
        if (position.getManagementState() == 1) {
            queryWrapper.clear();
            queryWrapper.lambda().eq(Position::getDepartmentId, position.getDepartmentId()).eq(Position::getManagementState, position.getManagementState());
            Position position1 = mapper.selectOne(queryWrapper);
            if (position1 != null) {
                throw new CustomException(ResultCode.POSITION_MANAGEMENT_STATE_ALREADY);
            }
        }
        position.setCreateTime(DateUtil.date());
        mapper.insert(position);
    }

    @Override
    public void update(Position position) {
        //修改时不能修改managementState状态
        Position p = mapper.selectById(position.getId());
        if (p == null) {
            throw new CustomException(ResultCode.DATA_NOT_FOUND);
        }
        position.setUpdateTime(DateUtil.date());
        mapper.updateById(position);
    }

    @Override
    public void deleteById(Integer positionId) {
        Position position = mapper.selectById(positionId);
        if (position == null) {
            throw new CustomException(ResultCode.DATA_NOT_FOUND);
        }
        //检测用户岗位中间表中是否有数据，有数据则不能删除，无数据则可以删除
        QueryWrapper<AdminPosition> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(AdminPosition::getPositionId, positionId);
        List<AdminPosition> adminPositions = positionMapper.selectList(queryWrapper);
        if (adminPositions.size() != 0) {
            throw new CustomException(ResultCode.ADMIN_RELEVANCY);
        }
        mapper.deleteById(positionId);
    }

    @Override
    public void deleteBySomeIds(String ids) {
        List<Integer> listIds = CovertUtil.covertIntegerList(ids);
        QueryWrapper<Position> wrapper = new QueryWrapper<>();
        if (listIds.size() != 0) {
            wrapper.lambda().in(Position::getId, listIds);
        }
        //wrapper.lambda().in(Position::getId,listIds);
        List<Position> positions = mapper.selectList(wrapper);
        if (positions.size() != listIds.size()) {
            throw new CustomException(ResultCode.DATA_NOT_FOUND);
        }
        //存在关联数据则不能删除
        QueryWrapper<AdminPosition> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().in(AdminPosition::getPositionId, listIds);
        List<AdminPosition> adminPositions = positionMapper.selectList(queryWrapper);
        if (adminPositions.size() != 0) {
            throw new CustomException(ResultCode.ADMIN_RELEVANCY);
        }
        mapper.delete(wrapper);
    }

    @Override
    public List<Admin> levelPermissions(Integer grade, String departmentId) {
        List<Integer> departmentIds = new ArrayList<>();

        if (StrUtil.isNotBlank(departmentId)) {
            departmentIds = CovertUtil.covertIntegerList(departmentId);
        }

//        if (grade == 0) grade = null;

        List<Admin> admins = mapper.levelPermissions(departmentIds, grade);

        if (grade == null) {
            List<Integer> finalDepartmentIds = departmentIds;
            admins.sort(((o1, o2) -> {
                int io1 = finalDepartmentIds.indexOf(o1.getDepartmentId());
                int io2 = finalDepartmentIds.indexOf(o2.getDepartmentId());
                if (io1 != -1) {
                    io1 = admins.size() - io1;
                }
                if (io2 != -1) {
                    io2 = admins.size() - io2;
                }
                return io2 - io1;
            }));
        }
        return admins;
    }


    @Override
    public List<Admin> chooseDepartment(String departmentId){
        List<Integer> departmentIds = CovertUtil.covertIntegerList(departmentId);

        List<Admin> admins = mapper.chooseDepartment(departmentIds);

        // 排序
        if(admins != null){
            List<Integer> finalDepartmentIds = departmentIds;
            admins.sort(((o1, o2) -> {
                int io1 = finalDepartmentIds.indexOf(o1.getDepartmentId());
                int io2 = finalDepartmentIds.indexOf(o2.getDepartmentId());
                if (io1 != -1) {
                    io1 = admins.size() - io1;
                }
                if (io2 != -1) {
                    io2 = admins.size() - io2;
                }
                return io2 - io1;
            }));
        }

        return admins;
    }
}

